package com.swf.seed.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swf.seed.base.SdCharset;
import com.swf.seed.base.SystemContants;

public class PropUtil {
	private static final Logger logger = LoggerFactory
			.getLogger(PropUtil.class);
    private static Properties prop;
    public static  String propFile = SystemContants.PROJECT_PATH+SystemContants.FILE_SEPARATOR+"config.properties";//默认属性文件路径
    
    
    /**
     * 修改默认配置文件
     * @param propFile
     */
    public static void changePropFile(String propFile){
    	if (new File(propFile).exists()){
    		PropUtil.propFile = propFile;
    		Properties props = new Properties();
    		try {
				props.load(new FileInputStream(propFile));
				prop = props;
			} catch (FileNotFoundException e) {
				logger.error(e.getMessage(), e);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
    	}else{
    		logger.error("配置文件不存在："+propFile);
    	}
    }
    
    public static Properties getProp(String proFilePath){
    	 Properties props = new Properties();
    	 try {
    		logger.debug("加载配置文件："+proFilePath);
			props.load(new FileInputStream(proFilePath));
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
    	 return props;
    }
    
    /**
     * 获取属性值
     * @param key 键
     * @return
     */
    public static String getPropValue(String key){
    	if (prop==null){
    		prop = getProp(propFile);
    	}
    	
    	if (prop == null){
    		return null;
    	}else {
    		return prop.getProperty(key);
    	}
    }
    
    /**
     * 获取指定编码的属性值
     * @param key   键
     * @param charst 字符编码
     * @return 属性值
     */
    public static String getPropValueByCharst(String key,String charst) {
    	String value = getPropValue(key);
    	if (value!=null){
    		try {
				value = new String(value.getBytes(SdCharset.ISO_8859_1),charst);
			} catch (UnsupportedEncodingException e) {
				logger.error(e.getMessage(),e);
			}
    	}
    	return value;
	}
    
	/**
	 * @param filePath properties文件路径
	 * @param key
	 * @return
	 */
	 public static String getPropValue(String proFilePath,String key) {
	    return getProp(proFilePath).getProperty(key);
	   }
	 /**
	  * 获取指定编码的属性值
	 * @param proFilePath 属性文件位置
	 * @param key  键
	 * @param charst  字符编码
	 * @return 属性值
	 */
	public static String getPropValueByCharst(String proFilePath,String key,String charst) {
		 String value =  getProp(proFilePath).getProperty(key);
			if (value!=null){
	    		try {
					value = new String(value.getBytes(SdCharset.ISO_8859_1),charst);
				} catch (UnsupportedEncodingException e) {
					logger.error(e.getMessage(),e);
				}
	    	}
	    	return value;
	 }
	
	
}
